﻿using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using System;
using System.Collections.Generic;

namespace Code.UI
{
    public class CardSelectPanel:MonoBehaviour
    {
        private CardSystem _cardSystem;
        private UIPlayer _uiPlayer;
        private Card _currentCard;
        
        [SerializeField] private GameObject _cardItem;
        [SerializeField] private Transform _cardListParent;
        [SerializeField] private Button _selectButton;
        [SerializeField] private float _animTime;

        private List<CardItem> _cardItems=new List<CardItem>();
        private void Awake()
        {
            _cardSystem = GameObject.FindObjectOfType<CardSystem>();
            _uiPlayer = GameObject.FindObjectOfType<UIPlayer>();

            foreach (var item in _cardSystem.GetCard(3))
            {
                var card=GameObject.Instantiate(_cardItem, _cardListParent);
                if(card.TryGetComponent<CardItem>(out var cardItem)) 
                {
                    cardItem.Init(item,_uiPlayer);
                    _cardItems.Add(cardItem);
                    cardItem.OnSelectCard += OnSelect;
                }
            } 
        }

        private void OnSelect(CardItem cardItem,Card card)
        {
            foreach (var item in _cardItems)
            {
                item.SetSelectMask(false);
            }
            cardItem.SetSelectMask(true);
            _currentCard = card;
        }

        private void Start()
        {
            transform.DOMove(new Vector3(transform.position.x,transform.position.y-900,transform.position.z),_animTime).OnComplete(()=> {
                _selectButton.gameObject.SetActive(true);
            });       
        }

        public void OnSelectButtonClicked() 
        {
            foreach (var item in _cardItems)
            {
                item.SetSelectMask(false);
            }

            if (_currentCard != null) 
            {
                _uiPlayer.UseCard(_currentCard);
                Debug.Log("选择并使用了该卡片");
                transform.DOMove(new Vector3(transform.position.x, transform.position.y + 900, transform.position.z), _animTime).OnStart(() => {
                    _selectButton.gameObject.SetActive(false);
                });
            }
            
        }
    }
}
